package auth

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"goskeleton/app/global/variable"
	"goskeleton/app/model"
	"goskeleton/app/utils/data_bind"
)

func CreateAuthPostMembersModelFactory(sqlType string) *AuthPostMembersModel {
	return &AuthPostMembersModel{BaseModel: model.BaseModel{DB: model.UseDbConn(sqlType)}}
}

type AuthPostMembersModel struct {
	model.BaseModel
	FrAuthOrganizationPostId int    `gorm:"column:fr_auth_organization_post_id" json:"org_post_id"`
	FrUserId                 int    `gorm:"column:fr_user_id" json:"user_id"`
	FrEmployeeId             int    `gorm:"column:fr_employee_id" json:"employee_id"`
	Status                   int    `json:"status"`
	Remark                   string `json:"remark"`
}

// 表名
func (a *AuthPostMembersModel) TableName() string {
	return "tb_auth_post_members"
}

// 查询类
func (a *AuthPostMembersModel) GetCount(postId float64, employeeName string) (count int64) {
	sql := `SELECT  count(*) as  counts  
			FROM    tb_auth_post_members  a,tb_employee  b   
			WHERE a.fr_employee_id=b.id  AND   ( a.fr_auth_organization_post_id=?  or 0=?)
			AND ( b.name  LIKE ?)
			`
	a.Raw(sql, postId, postId, "%"+employeeName+"%").First(&count)
	return
}
func (a *AuthPostMembersModel) List(postId, limitStart, limits int, employeeName string) (data []MemberList) {
	sql := `SELECT  a.id, a.fr_auth_organization_post_id AS org_post_id, a.fr_employee_id AS employee_id,b.name as employee_name,a.status,c.title AS post_name, a.remark, 
			a.created_at,a.updated_at  
			FROM    tb_auth_post_members  a,tb_employee  b   ,tb_auth_organization_post  c
			WHERE  a.fr_employee_id=b.id  AND c.id=a.fr_auth_organization_post_id
			AND    (a.fr_auth_organization_post_id=? or 0=?)
			AND  ( b.name  LIKE ?)
			LIMIT   ?,?`
	a.Raw(sql, postId, postId, "%"+employeeName+"%", limitStart, limits).Find(&data)
	return
}

// 新增
func (a *AuthPostMembersModel) InsertData(c *gin.Context) bool {
	var tmp AuthPostMembersModel
	if err := data_bind.ShouldBindFormDataToModel(c, &tmp); err == nil {
		var counts int64
		if res := a.Model(a).Where("fr_auth_organization_post_id=? AND  fr_employee_id=?", tmp.FrAuthOrganizationPostId, tmp.FrEmployeeId).Count(&counts); res.Error == nil && counts == 0 {
			// 显式指定表名，确保插入到正确的表中
			if res := a.Table(a.TableName()).Create(&tmp); res.Error == nil {
				return true
			} else {
				variable.ZapLog.Error("AuthPostMembersModel 新增失败", zap.Error(res.Error))
			}
		} else {
			variable.ZapLog.Warn("AuthPostMembersModel 不允许重复新增")
		}
	} else {
		variable.ZapLog.Warn("AuthPostMembersModel 数据绑定出错", zap.Error(err))
	}
	return false
}

// 新增
func (a *AuthPostMembersModel) InsertOneData(userId, employeeId, postId int) bool {
	var tmp AuthPostMembersModel
	tmp.FrAuthOrganizationPostId = postId
	tmp.FrUserId = userId
	tmp.FrEmployeeId = employeeId
	tmp.Status = 1
	tmp.Remark = "新增"

	var counts int64
	if res := a.Model(a).Where("fr_auth_organization_post_id=? AND  fr_employee_id=? AND fr_user_id=?", tmp.FrAuthOrganizationPostId, tmp.FrEmployeeId, tmp.FrUserId).Count(&counts); res.Error == nil && counts == 0 {
		if res := a.Create(&tmp); res.Error == nil {
			return true
		} else {
			variable.ZapLog.Error("AuthPostMembersModel 新增失败", zap.Error(res.Error))
		}
	} else {
		variable.ZapLog.Warn("AuthPostMembersModel 不允许重复新增")
	}

	return false
}

// 修改
func (a *AuthPostMembersModel) UpdateData(c *gin.Context) bool {
	var tmp AuthPostMembersModel
	if err := data_bind.ShouldBindFormDataToModel(c, &tmp); err == nil {
		// Omit 表示忽略指定字段(CreatedAt)，其他字段全量更新
		if res := a.Omit("CreatedAt").Save(&tmp); res.Error == nil {
			return true
		} else {
			variable.ZapLog.Error("AuthPostMembersModel 数据更新出错：", zap.Error(res.Error))
		}
	} else {
		variable.ZapLog.Error("AuthPostMembersModel 数据绑定出错：", zap.Error(err))
	}
	return false
}

// 删除
func (a *AuthPostMembersModel) DeleteData(id float64) bool {
	// 只能删除除了 admin 之外的用户
	var count int64
	a.Model(a).Select("fr_user_id").Where("id=?", id).First(&count)
	if count == 1 {
		return false
	}
	if res := a.Delete(a, id); res.Error == nil {
		return true
	} else {
		variable.ZapLog.Error("AuthPostMembersModel 删除数据出错：", zap.Error(res.Error))
	}
	return false
}

// 通过员工ID查询权限信息（新架构）
func (a *AuthPostMembersModel) GetByEmployeeId(employeeId int) []AuthPostMembersModel {
	var AuthPostMembersModel []AuthPostMembersModel
	a.Where("fr_employee_id = ? AND status = 1", employeeId).Find(&AuthPostMembersModel)
	return AuthPostMembersModel
}

// 通过用户ID查询权限信息（旧架构，保留兼容）
func (a *AuthPostMembersModel) GetByUserId(user_id int64) (AuthPostMembersModel []AuthPostMembersModel) {
	// 旧架构兼容：通过用户ID查找关联的员工，再查询权限
	// 这里需要联表查询，通过用户->员工->权限
	sql := `
		SELECT pm.id, pm.fr_auth_organization_post_id, pm.fr_employee_id, pm.status, pm.remark, pm.created_at, pm.updated_at
		FROM tb_auth_post_members pm
		INNER JOIN tb_employee e ON pm.fr_employee_id = e.id
		INNER JOIN tb_users u ON e.id = u.employee_id
		WHERE u.id = ? AND pm.status = 1
	`
	a.Raw(sql, user_id).Find(&AuthPostMembersModel)
	return
}

// 为用户-员工关联创建权限记录（新增方法，同时设置FrUserId和FrEmployeeId）
func (a *AuthPostMembersModel) CreateUserEmployeeAuth(userId, employeeId, orgPostId int, status int, remark string) bool {
	variable.ZapLog.Info("创建用户-员工权限记录",
		zap.Int("user_id", userId),
		zap.Int("employee_id", employeeId),
		zap.Int("org_post_id", orgPostId),
		zap.Int("status", status),
		zap.String("remark", remark))
	// 检查是否已存在相同的权限记录
	var count int64
	if err := a.Model(a).Where("(fr_user_id = ? OR fr_employee_id = ?) AND fr_auth_organization_post_id = ?",
		userId, employeeId, orgPostId).Count(&count).Error; err != nil {
		variable.ZapLog.Error("检查权限记录失败", zap.Error(err))
		return false
	}

	if count > 0 {
		variable.ZapLog.Warn("权限记录已存在，不允许重复创建")
		return false
	}

	// 创建新的权限记录，同时设置用户ID和员工ID
	newRecord := AuthPostMembersModel{
		FrAuthOrganizationPostId: orgPostId,
		FrUserId:                 userId,
		FrEmployeeId:             employeeId,
		Status:                   status,
		Remark:                   remark,
	}

	if err := a.Create(&newRecord).Error; err != nil {
		variable.ZapLog.Error("创建用户-员工权限记录失败", zap.Error(err))
		return false
	}

	variable.ZapLog.Info("成功创建用户-员工权限记录",
		zap.Int("user_id", userId),
		zap.Int("employee_id", employeeId),
		zap.Int("org_post_id", orgPostId))
	return true
}

// 通过用户ID和员工ID查询权限（支持双重查询）
func (a *AuthPostMembersModel) GetByUserAndEmployee(userId, employeeId int) []AuthPostMembersModel {
	var results []AuthPostMembersModel
	// 查询该用户ID或员工ID对应的权限记录
	a.Where("(fr_user_id = ? OR fr_employee_id = ?) AND status = 1", userId, employeeId).Find(&results)
	return results
}

// 删除用户-员工的权限关联
func (a *AuthPostMembersModel) DeleteUserEmployeeAuth(userId, employeeId int) bool {
	// 删除该用户和员工相关的所有权限记录
	if err := a.Where("fr_user_id = ? OR fr_employee_id = ?", userId, employeeId).Delete(&AuthPostMembersModel{}).Error; err != nil {
		variable.ZapLog.Error("删除用户-员工权限记录失败", zap.Error(err))
		return false
	}
	return true
}
